package com.dms.controller.backend;

import com.dms.common.Const;
import com.dms.common.ResponseCode;
import com.dms.common.ServerResponse;
import com.dms.pojo.File;
import com.dms.pojo.User;
import com.dms.service.IFileService;
import com.dms.service.IUserService;
import com.dms.service.impl.FileServiceImpl;
import com.dms.util.PropertiesUtil;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.xml.soap.Text;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/manage/file")
public class FileManageController {
    @Autowired
    private IUserService iUserService;

    @Autowired
    private IFileService iFileService;


    private Logger logger = LoggerFactory.getLogger(FileManageController.class);

    /**
     * 文件保存
     *
     * @param session
     * @param file
     * @return
     */
    @RequestMapping(value = "save.do", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse fileSave(HttpSession session, File file) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
        }

        if (iUserService.checkAdminRole(user).isSuccess()) {
            //填充增加的业务逻辑
            return iFileService.saveOrUpdateFile(file);
        } else {
            return ServerResponse.createByErrorMessage("无权这样操作");
        }
    }


    /**
     * 修改文件属性
     *
     * @param session
     * @param fileId
     * @param status
     * @return
     */
    @RequestMapping(value = "set_file_status.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse setFileStatus(HttpSession session, Integer fileId, Integer status) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
        }

        //检查用户权限
        if (iUserService.checkAdminRole(user).isSuccess()) {
            //填充增加的业务逻辑
            return iFileService.setFileStatus(fileId, status);
        } else {
            return ServerResponse.createByErrorMessage("无权这样操作");
        }
    }

    /**
     * 获取文件详情
     *
     * @param session
     * @param fileId
     * @return
     */
    @RequestMapping(value = "detail.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getDetail(HttpSession session, Integer fileId) {
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
        }

//        检查用户权限
        if (iUserService.checkAdminRole(user).isSuccess()) {
            //填充增加的业务逻辑
            return iFileService.manageFileDetail(fileId);
//            return   iFileService.setSaleStatus(fileId,status);
        } else {
            return ServerResponse.createByErrorMessage("无权这样操作");
        }
    }

    /**
     * 获取文件列表
     *
     * @param session
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "list.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getList(HttpSession session,
                                  @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                                  @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        if (session.getAttribute(Const.CURRENT_USER) == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "session为空");
        }
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
        }
        //检查用户权限
        if (iUserService.checkAdminRole(user).isSuccess()) {
            //填充增加的业务逻辑
            return iFileService.getFileList(pageNum, pageSize);
        } else {
            return ServerResponse.createByErrorMessage("无权这样操作");
        }
    }


    /**
     * 根据file名字查询
     *
     * @param session
     * @param filename
     * @param pi
     * @param ps
     * @return
     */
    @RequestMapping(value = "file_list.do", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<PageInfo> list(HttpSession session,
                                         @RequestParam(value = "filename", required = false) String filename,
                                         @RequestParam(value = "pi", defaultValue = "1") int pi,
                                         @RequestParam(value = "ps", defaultValue = "10") int ps) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (currentUser == null) {
            return ServerResponse.createByErrorMessage("用户没有登录");
        }

        return iFileService.searchFile(filename, pi, ps);
    }


    /**
     * 后台文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "upload.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse upload(HttpSession session, @RequestParam(value = "file", required = true) MultipartFile file, HttpServletRequest request) {

        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "用户未登录,请登录管理员");
        }

        //得到用户名
        String userName = user.getUsername();

        String path = request.getSession().getServletContext().getRealPath("upload");

        if (file == null) {
            System.out.println("file为空");
            return null;
        }

        String fileName = file.getOriginalFilename();
        //文件名
        String fileStartName = fileName.substring(0, fileName.indexOf("."));
//        logger.error(fileStartName);
        //扩展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);

        //原名+随机数+扩展名
        String Uuid = UUID.randomUUID().toString();
        String uploadFileName = fileStartName + "." + Uuid + "." + fileExtensionName;
        String targetFileName = iFileService.upload(file, path, uploadFileName);
        //判断上传成功或者失败
        if (targetFileName.equals(Const.UPLOAD_FAIL)) {
            return ServerResponse.createByErrorMessage("上传失败！");
        } else {
            File addFile = new File();
            addFile.setName(fileStartName);
            addFile.setUploader(userName);
            addFile.setAddress(uploadFileName);
            addFile.setType(fileExtensionName);
            return iFileService.saveOrUpdateFile(addFile);
        }

    }


    @RequestMapping(value = "save_file_date.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse SaveFilesData(Integer category_id, String name, String type, String address, Integer level, String uploader) {

        File file = new File();
        file.setCategoryId(category_id);
        file.setName(name);
        file.setType(type);
        file.setAddress(address);
        file.setLevel(level);
        file.setUploader(uploader);
        return iFileService.SaveFilesData(file);
    }


    @RequestMapping(value = "down_file.do", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse downFile(HttpSession session, String fileName, String realName, HttpServletRequest request) {
        String path = request.getSession().getServletContext().getRealPath("download");
        String fileNewName = realName + fileName.substring(fileName.lastIndexOf("."));

        logger.info(path);
        if (iFileService.download(path, fileName, fileNewName)) {
            return ServerResponse.createBySuccessMessage("下载成功");
        } else {
            return ServerResponse.createByErrorMessage("下载失败");
        }

    }


}
